package rpcserver

import (
	"path"
	"strings"
	"time"
)

func toUs(d time.Duration) string {
	// Largest time is 2540400h10m10.000000000s
	var buf [32]byte
	w := len(buf)

	u := uint64(d)
	neg := d < 0
	if neg {
		u = -u
	}
	var prec int
	// print microseconds
	w--
	buf[w] = 's'
	w--
	prec = 3
	// U+00B5 'µ' micro sign == 0xC2 0xB5
	w-- // Need room for two bytes.
	copy(buf[w:], "µ")
	w, u = fmtFrac(buf[:w], u, prec)
	w = fmtInt(buf[:w], u)

	if neg {
		w--
		buf[w] = '-'
	}

	return string(buf[w:])
}

func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
	// Omit trailing zeros up to and including decimal point.
	w := len(buf)
	print := false
	for i := 0; i < prec; i++ {
		digit := v % 10
		print = print || digit != 0
		if print {
			w--
			buf[w] = byte(digit) + '0'
		}
		v /= 10
	}
	if print {
		w--
		buf[w] = '.'
	}
	return w, v
}

// fmtInt formats v into the tail of buf.
// It returns the index where the output begins.
func fmtInt(buf []byte, v uint64) int {
	w := len(buf)
	if v == 0 {
		w--
		buf[w] = '0'
	} else {
		for v > 0 {
			w--
			buf[w] = byte(v%10) + '0'
			v /= 10
		}
	}
	return w
}

func lastChar(str string) uint8 {
	if str == "" {
		panic("The length of the string can't be 0")
	}
	return str[len(str)-1]
}

func joinPaths(absolutePath, relativePath string) string {
	if relativePath == "" {
		return absolutePath
	}

	absolutePath = strings.Replace(absolutePath, ".", "/", -1)
	relativePath = strings.Replace(relativePath, ".", "/", -1)

	finalPath := path.Join(absolutePath, relativePath)
	if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' {
		return finalPath + "/"
	}

	finalPath = strings.Replace(finalPath, "/", ".", -1)
	return finalPath
}
